package com.atguigu.gulimall.juc.demo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

public class ArrayBlockingQueueDemo {
    public static void main(String[] args) {
        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<String>(3);
//        blockingQueue.add("a");
//        blockingQueue.add("b");
//        blockingQueue.add("c");
//        blockingQueue.add("d"); // java.lang.IllegalStateException: Queue full

//        blockingQueue.remove();
//        blockingQueue.remove();
//        blockingQueue.remove();
//        blockingQueue.remove(); // java.util.NoSuchElementException

        try {
            blockingQueue.put("a");
            blockingQueue.put("b");
            blockingQueue.put("c");
            System.out.println("++++++++++++++++++++++++++++++");
//            blockingQueue.put("d"); // 阻塞住 ++++++++++++++++++++++++++++++ 没有 -----------------------------
//            System.out.println("-----------------------------");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            blockingQueue.take();
            blockingQueue.take();
            blockingQueue.take();
//            blockingQueue.take();// 阻塞住没有 =============================
            System.out.println("=============================");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("b"));
        System.out.println(blockingQueue.offer("c"));  // true
        System.out.println(blockingQueue.offer("d"));  // false


        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll()); // c
        System.out.println(blockingQueue.poll()); // null

        try {
            System.out.println(blockingQueue.offer("a",3, TimeUnit.SECONDS));
            System.out.println(blockingQueue.offer("b",3, TimeUnit.SECONDS));
            System.out.println(blockingQueue.offer("c",3, TimeUnit.SECONDS));
            System.out.println(blockingQueue.offer("d",3, TimeUnit.SECONDS)); // 等待三秒后程序终止
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        try {
            System.out.println(blockingQueue.poll(1,TimeUnit.SECONDS));
            System.out.println(blockingQueue.poll(1,TimeUnit.SECONDS));
            System.out.println(blockingQueue.poll(1,TimeUnit.SECONDS));
            System.out.println(blockingQueue.poll(1,TimeUnit.SECONDS)); // null
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
}
